import { history } from 'umi';
import React, { useState, useRef, useEffect, forwardRef } from 'react';
import { PageContainer, FooterToolbar, PageHeader } from '@ant-design/pro-layout';
import { TIMEFORMAT } from '@/utils/const';
import {
  Button,
  Divider,
  message,
  Input,
  Drawer,
  Table,
  Tabs,
  Card,
  Modal,
  Tag,
  Select,
  Descriptions,
  Popconfirm,
  Popover,
  List,
} from 'antd';
import style from './index.less';
import ProTable from '@ant-design/pro-table';
import ReactMarkdown from 'react-markdown';
import gfm from 'remark-gfm';
import { getModelInfo, getVersions, deleteVersions, versionList } from './service';
import format from '@/utils/format';
import { isBuffer, sortedLastIndexOf } from 'lodash';
import arouter from '@/utils/apulis-router';
import DetailInfo from './components/detailInfo.jsx';
import { AuthzHOC, AuthzProvider, useCheckAuth, checkAuth } from '@apulis/authz';
import ATable from '@apulis/table';
import { workshopRequest } from '@/utils/request';

// const { TextArea } = Input;
const imageDetail = (props, ref) => {
  // const [pageDetail, setPageDetail] = useState({});
  const [sorterOrder, setSorterOrder] = useState(''); // 控制排序
  const modelId = props.location.query.id; // 比传项 模型 ID
  const [info, setInfo] = useState({}); // 基础信息
  // const [versions, setVersions] = useState([]);
  const tableRef = React.useRef(); // 模型版本列表的ref
  const detailInfoRef = React.useRef(); // 模型版本详情的ref

  // 监听详细信息表格 change，实现 created 排序
  const tableChange = (pagination, filter, sorter) => {
    const sort = {
      descend: 'desc',
      ascend: 'asc',
    };
    const res = sort[sorter.order];
    if (res === undefined) {
      setSorterOrder(undefined);
      tableRef.cureent?.reload();
    } else {
      setSorterOrder(res);
    }
  };

  // 根据type-series格式显示设备
  function renderDevices(deviceList){
    if (!deviceList) return '';
    const len = deviceList.length;
    const str = deviceList[0].series ? `${deviceList[0].type}-${deviceList[0].series}` : deviceList[0].type;
    return (
      <>
        {len <= 1 ? <span>{str}</span> :
          <Popover content={
            <List dataSource={deviceList} renderItem={
              item => <List.Item>{item.series ? `${item.type}-${item.series}` : item.type}</List.Item>
            }>
            </List>
          }>
            <span>{str}</span>...
          </Popover>
        }
      </>
    )
  }

  const columns = [
    {
      title: '版本',
      dataIndex: 'name',
      render: (text, row) => {
        return (
          <a
            onClick={() => {
              detailInfoRef.current.open(row);
            }}
          >
            {text}
          </a>
        );
      },
    },
    {
      title: '版本描述',
      dataIndex: 'description',
      render: (text) => (
        <Popover content={text}>
          <span className='textEllipsis' style={{ display: 'inline-block'}}>
            {text}
          </span>
        </Popover>
      )
    },
    {
      title: '训练设备',
      dataIndex: 'trainDevices',
      render: renderDevices
    },
    {
      title: '中心推理设备',
      dataIndex: 'centerInferDevices',
      render: renderDevices
    },
    {
      title: '边缘推理设备',
      dataIndex: 'edgeInferDevices',
      render: renderDevices
    },
    {
      title: '训练引擎',
      dataIndex: 'engine',
      render: (text) => (
        <Popover content={text}>
          <span className='textEllipsis' style={{width: '300px', display: 'inline-block'}}>
            {text}{' '}
          </span>
        </Popover>
      )
    },
    // {
    //   title: '精度',
    //   dataIndex: 'centerInferPercision',
    // },
    // {
    //   title: '数据集',
    //   dataIndex: 'datasetName',
    // },
    {
      title: '创建人',
      dataIndex: 'publisher',
    },
    {
      title: '创建时间',
      dataIndex: 'publishTime',
      format: 'time',
      // render(text) {
      //   return format(text);
      // },
      sorter: true,
      // sorter: (a, b) => a.publishTime - b.publishTime,
    },
    {
      title: '操作',
      render(text, row) {
        return (
          <div>
            <AuthzHOC permission="/apworkshop/api/v1/studioModelVersion/{id}" action={['delete']}>
              <Popconfirm
                title="确认要删除模型版本吗?"
                onConfirm={() => {
                  console.log(text, row);
                  deleteVersions(row.versionId).then((res) => {
                    console.log(res);
                    if(res.code === 0){
                      message.success('删除成功');
                    }
                    tableRef.current.reload();
                  });
                }}
                onCancel={() => {
                  console.log('cancle');
                }}
                okText="Yes"
                cancelText="No"
              >
                <span className="ldm l-text-btn danger">删除</span>
              </Popconfirm>
            </AuthzHOC>
          </div>
        );
      },
    },
  ];

  useEffect(() => {
    getModelInfo(modelId).then((res) => {
      console.log(res);
      if (res.code === 0) {
        setInfo(res.data);
      }
    });
  }, []);

  return (
    <div>
      <PageContainer
        onBack={() => {
          arouter({ name: 'modelIndex' });
        }}
        title="模型详情"
      >
        <Card>
          <Descriptions title="基础信息">
            <Descriptions.Item label="模型名称">{info.name}</Descriptions.Item>
            <Descriptions.Item label="描述">{info.description}</Descriptions.Item>
            <Descriptions.Item label="版本数">{info.versionCount}</Descriptions.Item>
            <Descriptions.Item label="创建时间">{format(info.createdAt, TIMEFORMAT)}</Descriptions.Item>
            <Descriptions.Item label="主干网络">{info.backbone}</Descriptions.Item>
            <Descriptions.Item label="支持AutoDl">{info.autoDL ? '是' : '否'}</Descriptions.Item>
          </Descriptions>
          <Divider />
        </Card>
        <Card>
          <div className="ldm l-title" style={{ marginBottom: '20px' }}>
            模型版本列表
          </div>
          {/* 使用left-toobar则无法使用headerTitle,使用l-title代替 */}
          <ATable
            reloadIcon={false}
            request={workshopRequest}
            dataSourceAPIPath={`${versionList}/${modelId}`}
            columns={columns}
          ></ATable>
          {/* <ProTable
            className="ldm left-toolbar"
            options={false}
            actionRef={tableRef}
            search={false}
            rowKey={(r) => r.name}
            cardProps={{
              bodyStyle: { padding: 0 },
            }}
            pagination={{
              pageSize: 5,
            }}
            onChange={(pagination, filters, sorter) => tableChange(pagination, filters, sorter)}
            style={{ marginBottom: '20px' }}
            request={async (params, sorter, filter) => {
              console.log(params, sorter, filter);
              const res = await getVersions(
                modelId,
                {
                  pageNum: params.current,
                  pageSize: params.pageSize,
                  sort: sorterOrder?`createdAt|${sorterOrder}`:'',
                },
                modelId,
              );
              if (res.code === 0) {
                console.log(res.data);
                return {
                  data: res.data.items,
                  success: true,
                  total: res.data.total,
                };
              }
            }}
            columns={columns}
          /> */}
          <div className="ldm l-title" style={{ marginBottom: '20px' }}>
            模型介绍
          </div>
          <div className={style.article}>
            <ReactMarkdown plugins={[[gfm, { singleTilde: false }]]} allowDangerousHtml>
              {info.readMe}
            </ReactMarkdown>
          </div>
          {/* 模型介绍使用富文本展示，以下属性是 react 标签属性，其中第一个 {} 代表jsx，第二个接受键值对 */}
          {/* <div dangerouslySetInnerHTML={{__html: info.readMe}}></div> */}
          {/* <pre>{info.description}</pre> */}
          {/* <TextArea placeholder="" autoSize={{ minRows: 2,}} disabled/> */}
        </Card>
      </PageContainer>
      <DetailInfo ref={detailInfoRef} />
    </div>
  );
};

export default imageDetail;
